<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/29
 * Time: 14:23
 */

namespace app\api\controller;


use app\common\controller\Base;
use think\Db;
use think\Cache;
use app\common\logic\Pocessing;
use think\Cookie;

header("ACCESS-CONTROL-ALLOW-ORIGIN:http://114.215.68.205");

class Game extends Base
{
    public function _initialize(){

        header("Content-type:text/html;charset=utf-8");
        parent::_initialize();
        $start = array(
            'user_all'                     => $this->user_all,
            'app_down'                 => $this->app_down,
            'logo'                          => $this->logo,
            'now_time_windows' => $this->now_time_windows
        );
        //判断投注功能是否开启
        $zhuh_class_ifopen = Db::name('xt_tzms')->find();
        if($zhuh_class_ifopen['chedan']) {
            $this->chedan = 1;
        } else {
            $this->chedan = 0;
        }
        //判断追号功能是否开启
        if($zhuh_class_ifopen['zhuihao']) {
            $this->zhuihao = 1;
        } else {
            $this->zhuihao = 0;
        }
        $this->lot = new Pocessing();
        $this->assign('cur','shop');
        $this->assign($start);
        $this->assign('chedan',$this->chedan);
        $this->assign('zhuihao',$this->zhuihao);

        //验证加密
        $VALUE_KEY = ['afewfewfew21342dsaewf'=>'8f4da4f9ew4f98ewq65fwe48f9w'];
        $HEADER_TIME = isset($_SERVER['HTTP_TIME']) ? $_SERVER['HTTP_TIME'] : '';
        $HEADER_KEY = isset($_SERVER['HTTP_KEY']) ? $_SERVER['HTTP_KEY'] : '';
        $HEADER_SIGN = isset($_SERVER['HTTP_SIGN']) ? $_SERVER['HTTP_SIGN'] : '';

        $POST_LOGIN_KEY = isset($_SERVER['HTTP_LOGINKEY']) ? $_SERVER['HTTP_LOGINKEY'] : ( isset($_POST['login_key']) ? $_POST['login_key'] : '' );
        $POST_NAME = isset($_SERVER['HTTP_USERNAME']) ? $_SERVER['HTTP_USERNAME'] : (isset($_POST['username']) ? $_POST['username'] : (isset($_POST['name']) ? $_POST['name']:''));


        if( !isset($VALUE_KEY[$HEADER_KEY]) ){
            exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
        }

        $validation =  $HEADER_TIME.$VALUE_KEY[$HEADER_KEY].$POST_LOGIN_KEY.$POST_NAME;
        if( $HEADER_SIGN != md5($validation) ){
            exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
        }
    }
    /**
     ** 投注页
     ** @param $game_id [string 对应彩种的id]
     **/
    public function index()
    {
        $gameid = input('game_id') ? input('game_id') : '';

        if(empty(Cookie::get('game_id'))){
            Cookie::set('game_id',$gameid);
        }else if($gameid != Cookie::get('game_id')){
            Cookie::clear('wanfa_tzhm_');
            Cookie::clear('wanfa_digit_');
            Cookie::set('game_id',$gameid);
        }
        $wer = [76,77,78,79,80,81,82,83,84,85,93,94,95,96,126,105,120,141];
        $this->assign('wer',$wer);
        if(!$gameid || $gameid < 1)  {
            mobile_tishi('非法操作！','/mobile/Bet/index',$this->appfrom);return;
        }
        //即时注单
        $caizhong = Db::name('caipai_list')->where('cp_if_open<2')->select();
        $time = date('Y-m-d',time());
        $star = strtotime($time.'00:00:00');
        $end = strtotime($time.'23:59:59');
        $zh = 0;$sy=0;
        foreach ($caizhong as $key => &$v){
            $where['czid'] = $v['id'];
            $where['username'] = $this->user_all['username'];
            $where['tz_time'] = ['between',$star.','.$end];
            $tz_no = Db::name('touzhu_list_no')->where($where)->select();
            foreach($tz_no as $v_no){
                $zh += $v_no['tzje'];
            }
            $tz_ok = Db::name('touzhu_list_ok')->where($where)->select();
            foreach ($tz_ok as $v_ok){
                $zh += $v_ok['tzje'];
                $sy += $v_ok['zjje'];
            }
        }
        $sy = $sy-$zh;
        $sy = sprintf("%.2f",$sy);
        $zh = sprintf("%.2f",$zh);
        $this->assign('zh',$zh);
        $this->assign('sy',$sy);
        //元角分设置
        $yjf = Db::name('xt_tzms')->where('id',1)->find();
        //获取路径名称
        $lottey_class = Db::name('lottery_classify')->select();
        $class_sign='';
        $id = '';
        $fandian=0;
        $sign = array();
        foreach ($lottey_class as $class){
            $sign = explode(',', $class['czids']);
            $t = in_array($gameid, $sign);
            if($t){
                $class_sign = $class['class_sign'];
                $fandian = $class['fandian'];
                $id = $class['id'];
            }
        }
        $play_id = input('xflid')?input('xflid'):'';
        $way_id = input('dflid')?input('dflid'):'';


        //小分类默认第一个
        if($play_id == ''){
            $xfli = Db::name('caipai_list')->where('id',$gameid)->order('id','ASC')->limit(1)->value('initial_class_id');
            $play_id= $xfli;
            //大分类默认第一个
            if($way_id == ''){
                $wfids = Db::name('play_classify')->where('id',$play_id)->order('id','ASC')->limit(1)->value('way_class_id');
                $way_id= $wfids;
            }
        }
        //echo $way_id.'#'.$play_id;

        //大分类
        $fenlei = Db::name('way_classify')->where('lottery_class_id',$id)->select();

        $xfl = Db::name('play_classify')->where('way_class_id',$way_id)->select();
        //分类显示
        $fx = Db::name('way_classify')->where('lottery_class_id',$id)->where('id',$way_id)->value('class_name');
        $xf = Db::name('play_classify')->where('way_class_id',$way_id)->where('id',$play_id)->find();

        $this->assign('xf',$xf['name_ab']);
        $this->assign('fx',$fx);
        $this->assign('fenlei',$fenlei);
        $this->assign('xfl',$xfl);
        $this->assign('play_id',$play_id);
        $this->assign('wayid',$way_id);
        //赔率
        $wf_info = Db::name('peilv')->field('id,peilv_name,zgpl,zdpl')->where('id','IN',$xf['peilv_ids'])->select();
        $wf_info_json = $wf_info;
        $peilvs = '';
        foreach ($wf_info_json as &$v){
            if($play_id == 2 || $play_id == 10 || $play_id == 16 || $play_id == 188 || $play_id == 204) {
                //为组合玩法组装赔率
                $peilvs .= $v['zgpl'] . '|';
            }
            unset($v['id']);
            unset($v['peilv_name']);
        }


        $wf_info_json = json_encode($wf_info_json);
        $wf_info['wanfa'] = $xf['class_name_mini'];
        $peilvs = $peilvs ? $peilvs : $wf_info[0]['zgpl'];

        $f = Db::name('username')->where('username',$this->user_all['username'])->find();
        $kjjg = Db::name('kjjg_list')->where('czid',$gameid)->where('iftz',1)->order('qihao desc')->find();
        $kj = kjjg_split($kjjg['kjjg'], $kjjg['czid']);
        /**
         * @todo 获取开奖结果的和值、单双、大小
         */
        $arr = getExtInfo($gameid,$kj);

        $caizhong = Db::name('caipai_list')->where('id',$gameid)->find();
        //最近五期开奖结果
        $zjkjjg = Db::name('kjjg_list')->field('czid,qihao,kjjg,0 as he,0 as dx,0 as ds')->where('czid',$gameid)->where('iftz',1)->order('id DESC')->limit(5)->select();
        foreach($zjkjjg as &$val){
            $val['kjjg'] = kjjg_split($val['kjjg'], $val['czid']);
            foreach ($val['kjjg'] as $it){
                $val['he'] += $it;
                if($val['he']%2==1){
                    $val['ds']='单';
                }else{
                    $val['ds']='双';
                }
                if($val['czid']==1 || $val['czid']==62 || $val['czid']==8){
                    if($val['he']>22){
                        $val['dx']='大';
                    }else{
                        $val['dx']='小';
                    }
                }
                if($val['czid']==5 || $val['czid']==7 || $val['czid']==48 || $val['czid']==10){
                    if($val['he']>13){
                        $val['dx']='大';
                    }else{
                        $val['dx']='小';
                    }
                }
                if($val['czid']==44 || $val['czid']==36|| $val['czid']==72){
                    if($val['he']>10){
                        $val['dx']='大';
                    }else{
                        $val['dx']='小';
                    }
                }
                if($val['czid']==51){
                    if($val['he']>31){
                        $val['dx']='大';
                    }else{
                        $val['dx']='小';
                    }
                }
            }
        }

        $kjjg_data_fur = Db::name('kjjg_list')->field('jztime')->where('czid',$gameid)->where('jztime','>',time())->where('kjjg','0')->order('qihao','ASC')->find();
        $kjjg_data_fur['jztime'] = $kjjg_data_fur['jztime'] ? $kjjg_data_fur['jztime'] : time();
        $jztime_fur = $kjjg_data_fur['jztime'] - time();
        $jztime_fur_r = floor($jztime_fur)-$caizhong['cp_fp_time'];
        $jzt = $kjjg_data_fur['jztime'];
        $this->assign('jzt',$jzt);
     	if($jztime_fur_r<=0){
        	$h_m_s['hl']='已';
        	$h_m_s['ml']='封';
        	$h_m_s['sl']='盘';
        }else{
	        $h_m_s['hl'] = floor(($jztime_fur_r / 3600) % 24);
	        $h_m_s['ml'] = floor(($jztime_fur_r / 60) % 60);
	        $h_m_s['sl'] = floor($jztime_fur_r % 60);
	        if($h_m_s['hl'] <10) $h_m_s['hl'] = '0'.$h_m_s['hl'];
	        if($h_m_s['ml'] <10) $h_m_s['ml'] = '0'.$h_m_s['ml'];
	        if($h_m_s['sl'] <10) $h_m_s['sl'] = '0'.$h_m_s['sl'];
        }
     	if($jztime_fur<=0){
        	$h_m_s['h']='开';
        	$h_m_s['m']='奖';
        	$h_m_s['s']='中';
        }else{
        	$h_m_s['h'] = floor(($jztime_fur / 3600) % 24);
        	$h_m_s['m'] = floor(($jztime_fur / 60) % 60);
        	$h_m_s['s'] = floor($jztime_fur % 60);
	        if($h_m_s['h'] <10) $h_m_s['h'] = '0'.$h_m_s['h'];
	        if($h_m_s['m'] <10) $h_m_s['m'] = '0'.$h_m_s['m'];
	        if($h_m_s['s'] <10) $h_m_s['s'] = '0'.$h_m_s['s'];
        }

        $this->assign('h_m_s',$h_m_s);
        $this->assign('jztime_fur',$jztime_fur);
        $this->assign('jztime_fur_r',$jztime_fur_r);

        //购物车
        $shopping = $_COOKIE;
        $car_shopping = array();
        $no_tzhm_old = '';
        $count=0;
        $Q_hj=0;
		
        foreach ($shopping as $k=>$value){
        	Cookie::delete('wanfa_tzhm_');
            if(strstr($k, 'wanfa_tzhm_')!==false  && strlen($k)>12){

                $key = substr($k, 11);
                $car_shopping[$key] = explode('[G]', $value);
                $v= trim(substr($value,0,strrpos($value, '[G]')));

                if(trim(strrchr($value, '[G]'),'[G]')==$gameid){
                    $no_tzhm_old .= "biaoshi_".$key.'[SH]'.$v.'[H]';
                }

            }
        }

        foreach ($car_shopping as &$va){
            $va[0]=explode(',', $va[0]);
            $qu = Db::name('play_classify')->where('id',$va[7])->value('class_name_mini');
            $va[7] = $qu;
            $count += $va[3];
            $Q_hj += $va[2];

        }

        $play_mini = Db::name('play_classify')->column('id,class_name_mini');
        $this->assign('mini',json_encode($play_mini,JSON_UNESCAPED_UNICODE));

        $no_tzhm_old = rtrim($no_tzhm_old,'[H]');
        $kjjg_data_cur = Db::name('kjjg_list')->where('czid',$gameid)->where('jztime','<',time())->where('kjjg','<>','0')->order('jztime','DESC')->find();
        $kjjg_data_fur = Db::name('kjjg_list')->where('czid',$gameid)->where('jztime','>',time())->where('kjjg','0')->order('qihao','ASC')->find();
        $ext = Db::name('kjjg_list')->where('czid',$gameid)->field('qihao')->order('qihao','DESC')->find();
        $this->assign('qihao_quan',$ext['qihao']);
        if($gameid==62 || $gameid==63 || $gameid==72){
        	$ext['qihao'] = substr($ext['qihao'], 4);
        }
        $yue = Db::name('username')->where('username',$this->user_all['username'])->value('je');
		$this->assign('yue',$yue);
        $this->assign('qihao_zx',$ext['qihao']);
        $this->assign('qihao_cur',$kjjg_data_cur['qihao']);
        $this->assign('qihao_fur',$kjjg_data_fur['qihao']);
        $this->assign('tz_cookie_num',count($car_shopping));
        $this->assign('no_tzhm_old',$no_tzhm_old);
        $this->assign('Q_hj',$Q_hj);
        $this->assign('cou',$count);
        $this->assign('car_shopping',$car_shopping);
        $this->assign('game_id',$gameid);
        $this->assign('zjkjjg',$zjkjjg);
        $this->assign('wf_info_json',$wf_info_json);
        $this->assign('wf_info',$wf_info);
        $this->assign('count',count($kj));
        $this->assign('arr',$arr);
        $this->assign('kjjg',$kj);
        $this->assign('qihao',$kjjg['qihao']);
        $this->assign('f',$f);
        $this->assign('yjf',$yjf);
        $this->assign('fandian',$fandian);
        $this->assign('time',time());
        $this->assign('peilvs',$peilvs);
        $this->assign('fenlei',$fenlei);
        $this->assign('caizhong',$caizhong);
        $this->assign('game_id',$gameid);
        $html_class = "/game/".$class_sign."/class_".$play_id;
        return $this->fetch($html_class);
    }
    public function jishizhudan(){
        if(!$this->user_all['id']) {
            if( 1==$this->appfrom ){
                echo '<script>jump2app.jump2LoginActivity();jump2app.destroyWebActivity();</script>';return;
            }elseif(2==$this->appfrom){
                $string = "function setupWebViewJavascriptBridge(callback) {
                                if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
                                if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
                                window.WVJBCallbacks = [callback];
                                var WVJBIframe = document.createElement('iframe');
                                WVJBIframe.style.display = 'none';
                                WVJBIframe.src = 'https://__bridge_loaded__';
                                document.documentElement.appendChild(WVJBIframe);
                                setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
                            }";
                $string .= "setupWebViewJavascriptBridge(function(bridge) {
                                /* Initialize your app here */
                                bridge.registerHandler('JS Echo', function(data, responseCallback) {
                                    console.log(\"JS Echo called with:\", data)
                                    responseCallback(data)
                                })
                                bridge.callHandler('jumpToLogin', {'key':'value'}, function responseCallback(responseData) {
                                    console.log(\"JS received response:\", responseData)
                                })
                            })".PHP_EOL;
                $string .= "WebViewJavascriptBridge.callHandler('jumpToLogin');";
                echo "<script>".$string."</script>";
                return;
            }
        }
        $touzhu = Db::name('touzhu_list_no')
            ->alias('a')
            ->join('__CAIPAI_LIST__ b','b.id=a.czid')
            ->field('a.*,b.cp_name_old,b.cp_name_new')
            ->where('username',$this->user_all['username'])->select();
        foreach ($touzhu as $key => &$v){
            if($key%2 == 0){
                $v['ds']=1;
            }else{
                $v['ds']=2;
            }
        }
        $this->assign('caizhong',$touzhu);
        return $this->fetch();
    }
}